package com.yonyou.pmclouds.plan.service;

import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.ref.itf.RefCodeConst;
import com.yonyou.pmclouds.basecom.ref.itf.ReferenceCheckOfBusiness;
import com.yonyou.pmclouds.plan.mapper.PlanTempletMapper;
import com.yonyou.pmclouds.plan.mapper.ProjectPlanMapper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PlanReferBdCheck implements ReferenceCheckOfBusiness {
    @Autowired
    private ProjectPlanMapper mapper;
    @Autowired
    private PlanTempletMapper templetMapper;

    @Override
    public String[] getReferenceCode() {
        return new String[]{RefCodeConst.PROJECT, RefCodeConst.MILESTONE};
    }

    @Override
    public boolean checkReferenced(String bdCode, String[] keys) throws BusinessException {
        if (!RefCodeConst.PROJECT.equals(bdCode) && !RefCodeConst.MILESTONE.equals(bdCode)) {
            return false;
        }
        if (ArrayUtils.isEmpty(keys)) {
            return false;
        }
        int count = 0;
        for (String key : keys) {
            if (RefCodeConst.PROJECT.equals(key)) {
                count = mapper.countRootPlanOfProject(key);
            } else {
                // 校验里程碑是否被引用
                count = mapper.countMilestoneRelatedPlan(key);
                if (count == 0)
                    count = templetMapper.countMilestoneRelatedPlan(key);
            }
            if (count > 0) {
                return true;
            }
        }
        return false;
    }
}
